package ua.at.tsvetkov.samizdat.adapters;

import java.text.SimpleDateFormat;
import java.util.Date;

import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.R;
import ua.at.tsvetkov.samizdat.database.ContentProviderSamizdat;
import android.app.Fragment;
import android.database.Cursor;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FilterQueryProvider;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class AdtBooks extends SimpleCursorAdapter {

	private Fragment				fragment;
	private Cursor					cursor;
	private AuthorsHolder		authorsHolder;
	private RelativeLayout		loadingView;

	private Integer				currentGenresClickedPosition	= -1;
	private Boolean				enableAnnotation					= false;

	private final static int	CURRENT_LOADING_VIEW_ID			= 102;

	static class AuthorsHolder {
		public TextView	title;
		public TextView	author;
		public TextView	date;
		public TextView	ball;
		public TextView	annot;
	}

	public AdtBooks(Fragment fragment) {
		super(fragment.getActivity(), R.layout.frg_books_list_view_item, null, new String[] { Const.TITLE, Const.AUTHOR, Const.BALL, Const.DATE, Const.ANNOT }, new int[] {
				R.id.frg_books_list_view_item_title, R.id.frg_books_list_view_item_authors, R.id.frg_books_list_view_item_ball, R.id.frg_books_list_view_item_date,
				R.id.frg_books_list_view_item_annotation });
		this.fragment = fragment;
		setFilterQueryProvider(getAdapterBooksFilterQueryProvider());
		initLoadingView();
	}

	@Override
	public void changeCursor(Cursor cursor) {
		if (cursor != null) {
			super.changeCursor(cursor);
			this.cursor = cursor;
		}
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater inflater = fragment.getActivity().getLayoutInflater();
			convertView = inflater.inflate(R.layout.frg_books_list_view_item, null);
			authorsHolder = new AuthorsHolder();
			authorsHolder.title = (TextView) convertView.findViewById(R.id.frg_books_list_view_item_title);
			authorsHolder.author = (TextView) convertView.findViewById(R.id.frg_books_list_view_item_authors);
			authorsHolder.date = (TextView) convertView.findViewById(R.id.frg_books_list_view_item_date);
			authorsHolder.ball = (TextView) convertView.findViewById(R.id.frg_books_list_view_item_ball);
			authorsHolder.annot = (TextView) convertView.findViewById(R.id.frg_books_list_view_item_annotation);
			convertView.setTag(authorsHolder);
		} else {
			authorsHolder = (AuthorsHolder) convertView.getTag();
		}

		cursor.moveToPosition(position);

		authorsHolder.title.setText(cursor.getString(1));
		authorsHolder.author.setText(cursor.getString(2));
		authorsHolder.ball.setText(cursor.getString(3));
		Date date = new Date(cursor.getLong(4));
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		authorsHolder.date.setText(dateFormat.format(date));

		if (enableAnnotation) {
			authorsHolder.annot.setText(cursor.getString(5));
			authorsHolder.annot.setVisibility(View.VISIBLE);
		} else {
			authorsHolder.annot.setText("");
			authorsHolder.annot.setVisibility(View.GONE);
		}

		return convertView;
	}

	private void initLoadingView() {
		LayoutInflater li = LayoutInflater.from(fragment.getActivity());
		loadingView = (RelativeLayout) li.inflate(R.layout.frg_books_loading_view, null);
		loadingView.setId(CURRENT_LOADING_VIEW_ID);
		RelativeLayout parentView = (RelativeLayout) fragment.getView();
		parentView.addView(loadingView);
		loadingView.setVisibility(View.GONE);
	}

	public void refreshListWithId(final int id) {
		
		refreshListViewWithIdAndAnnotation(id, enableAnnotation);
		
	}

	public void refreshListViewWithIdAndAnnotation(final int id, final boolean enableAnnotation) {

		refreshListViewWithIdAndAnnotationAndOrder(id, enableAnnotation, null);

	}

	public void refreshListViewWithIdAndSortOrder(final int id, final String sortOrder) {
		
		refreshListViewWithIdAndAnnotationAndOrder(id, enableAnnotation, sortOrder);
	}

	public void refreshListViewWithIdAndAnnotationAndOrder(final int id, final boolean enableAnnotation, final String sortOrder) {
		currentGenresClickedPosition = id;
		loadingView.setVisibility(View.VISIBLE);
		this.enableAnnotation = enableAnnotation;

		new Thread(new Runnable() {
			@Override
			public void run() {
				StringBuffer pattern = new StringBuffer(Const.clearPattern);
				final Cursor cursor = fragment
						.getActivity()
						.getContentResolver()
						.query(Uri.parse(ContentProviderSamizdat.BOOK_CONTENT_URI + "/"), new String[] { Const.ID, Const.TITLE, Const.AUTHOR, Const.BALL, Const.DATE, Const.ANNOT },
								Const.BOOK_GENRES + " LIKE " + " '" + pattern.replace(id, id + 1, "1") + "'", null, sortOrder);
				if (fragment.getActivity() != null) {
					fragment.getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							changeCursor(cursor);
							notifyDataSetChanged();
							loadingView.setVisibility(View.GONE);
						}
					});
				}
			}
		}).start();
	}

	private FilterQueryProvider getAdapterBooksFilterQueryProvider() {
		return new FilterQueryProvider() {
			public Cursor runQuery(final CharSequence constraint) {

				new Thread(new Runnable() {
					@Override
					public void run() {
						final Cursor currentCursor;
						fragment.getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								loadingView.setVisibility(View.VISIBLE);
							}
						});
						if (constraint != null && constraint.toString().length() > 0) {
							StringBuffer pattern = new StringBuffer(Const.clearPattern);
							currentCursor = fragment
									.getActivity()
									.getContentResolver()
									.query(
											Uri.parse(ContentProviderSamizdat.BOOK_CONTENT_URI + "/"),
											new String[] { Const.ID, Const.TITLE, Const.AUTHOR, Const.BALL, Const.DATE, Const.ANNOT  },
											Const.BOOK_GENRES + " LIKE " + " '" + pattern.replace(currentGenresClickedPosition, currentGenresClickedPosition + 1, "1") + "'" + " AND " + Const.TITLE + " LIKE "
													+ " '" + constraint.toString() + "%'", null, "_id asc limit 100");
						} else {
							StringBuffer pattern = new StringBuffer(Const.clearPattern);
							currentCursor = fragment
									.getActivity()
									.getContentResolver()
									.query(Uri.parse(ContentProviderSamizdat.BOOK_CONTENT_URI + "/"), new String[] { Const.ID, Const.TITLE, Const.AUTHOR, Const.BALL, Const.DATE, Const.ANNOT  },
											Const.BOOK_GENRES + " LIKE " + " '" + pattern.replace(currentGenresClickedPosition, currentGenresClickedPosition + 1, "1") + "'", null, null);
						}
						fragment.getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								loadingView.setVisibility(View.GONE);
								changeCursor(currentCursor);
							}
						});
					}
				}).start();
				return null;
			}
		};
	}
}
